package jsu.lipengcheng.trafficnet.service.Impl;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import jakarta.servlet.http.HttpServletResponse;
import jsu.lipengcheng.trafficnet.common.BeanThread;
import jsu.lipengcheng.trafficnet.common.PageResult;
import jsu.lipengcheng.trafficnet.handler.UserEX;
import jsu.lipengcheng.trafficnet.mapper.TicketMapper;
import jsu.lipengcheng.trafficnet.mapper.UserMapper;
import jsu.lipengcheng.trafficnet.pojo.Ticket;
import jsu.lipengcheng.trafficnet.pojo.TicketExportDTO;
import jsu.lipengcheng.trafficnet.pojo.TicketVO;
import jsu.lipengcheng.trafficnet.pojo.Users;
import jsu.lipengcheng.trafficnet.service.TicketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static java.lang.Integer.parseInt;

@Service
public class TicketServiceImpl implements TicketService {
    @Autowired
    private TicketMapper ticketMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 查询用户的发单
     * @return
     */
    public List<TicketVO> selectuserbyid() {
        Integer id = BeanThread.get();
        List<TicketVO> ticketVO= ticketMapper.selectByUserId(id);
        return ticketVO;
    }

    /**
     * 管理员查看所有用户罚单
     * @return
     */
    public PageResult selectall(Integer userId, LocalDate createTime,int page, int pageSize) {
        PageHelper.startPage(page,pageSize);
       List<TicketVO> ticketVOList= ticketMapper.selectallbytime(userId,createTime);
        Page<TicketVO> page1=(Page<TicketVO>)ticketVOList;
        PageResult pageResult=new PageResult(page1.getTotal(),page1.getResult());
        return pageResult;
    }

    /**
     * 添加用户罚单
     * @param ticket
     */
    public void insertticket(Ticket ticket) {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        // 生成随机数
        String randomNum = String.format("%04d", new Random().nextInt(10000));
        // 拼接订单号
       String name= timestamp + randomNum;
        ticket.setFineNumber(name);
        ticket.setStatus(0);
        ticket.setCreateTime(LocalDate.now());
        ticketMapper.insert(ticket);
        //修改用户交通分数
        Users user = new Users();
        user.setId(ticket.getUserId());
        Users users = userMapper.selectById(ticket.getUserId());
        int kofen= Integer.parseInt(ticket.getUpdataScore());
        if(users.getScore()-kofen>0){
            user.setScore(users.getScore()-kofen);
        }
        else {
            user.setScore(0);
        }
        userMapper.updateById(user);
    }

    /**
     * 修改用户罚单
     * @param ticket
     */
    public void updateticket(Ticket ticket) {
        ticketMapper.updateById(ticket);
        Users user = new Users();
        user.setId(ticket.getUserId());
        Users users = userMapper.selectById(ticket.getUserId());
        int kofen= Integer.parseInt(ticket.getUpdataScore());
        if(users.getScore()-kofen>0){
            user.setScore(users.getScore()-kofen);
        }
        else {
            user.setScore(0);
        }
        userMapper.updateById(user);
    }

    /**
     * 根据id查询用户罚单
     * @param id
     * @return
     */
    public Ticket selectbyid(int id) {
        Ticket ticket = ticketMapper.selectById(id);
        return ticket;
    }

    /**
     * 删除罚单
     * @param id
     */
    public void deleteticket(int id) {
        ticketMapper.deleteById(id);
    }

    @Override
    public int selectsum() {
       int sum= ticketMapper.selectsum();
        return sum;
    }

    /**
     * 批量导出
     */
    public void donwload(HttpServletResponse response) throws IOException {
        List<Ticket> list = ticketMapper.selectList(null);

        if (list == null || list.isEmpty()) {
            throw new UserEX("未找到数据");
        }

        // 转换为 DTO 列表
        List<TicketExportDTO> dtoList = new ArrayList<>();
        for (Ticket ticket : list) {
            dtoList.add(TicketExportDTO.from(ticket));
        }

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");

        // 防止中文乱码
        String fileName = URLEncoder.encode("罚单数据", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 使用 EasyExcel 写出 Excel
        EasyExcel.write(response.getOutputStream(), TicketExportDTO.class)
                .autoCloseStream(true)
                .sheet("罚单信息")
                .doWrite(dtoList);
    }
    @Override
    public void saveBatch(List<Ticket> tickets) {
        for (Ticket ticket : tickets) {
            insertticket(ticket); // 复用你已有的 insertticket 方法
        }
    }
}
